﻿using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Singer.Framework.CoreFilters;
using Singer.Shared.UserContext;

namespace Singer.Framework;

/// <summary>
/// 基础服务 拓展
/// </summary>
public static class CoreServiceExtensions
{
    /// <summary>
    /// 注册基础拓展服务
    /// </summary>
    public static void AddCores(this IServiceCollection services)
    {
        services.AddControllers(opt =>
        {
            // opt.Filters.Add<CoreApiExceptionFilter>();//全局异常处理过滤器
            opt.Filters.Add<CoreApiResultFilter>();//全局Api结果处理过滤器
            opt.Filters.Add<ModelValidateActionFilter>();// 自定义接口模型验证过滤器
        }).ConfigureApiBehaviorOptions(opt =>
        {
            opt.SuppressModelStateInvalidFilter = true;// 禁用默认的模型验证过滤器
        }).AddNewtonsoftJson(opt =>//json格式处理
        {
            opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;//忽略循环引用
            opt.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";//时间转字符串格式
            opt.SerializerSettings.Converters.Add(new StringEnumConverter());//枚举转字符串
            opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        });
        services.AddSingleton<IUserContextAccessor, UserContextAccessor>();//用户信息上下文
    }
}
